<?php

namespace platform\models;

use common\services\Authorization;
use platform\core\BaseModel;
use cm;
use Yii;
use yii\helpers\Url;

class CircuitModel extends BaseModel
{
    /*
    * 线路管理
    */
    public function actionIndex()
    {
        if (Cm::$req->isPost()) {
            $action = Cm::$req->get('action');
            switch ($action) {
                case "list":
                    $key = Cm::$req->post('key', ['null', 'empty', 'default' => '']);
                    $status = (int)Cm::$req->post('is_status', ['null', 'empty']);
                    $hot = (int)Cm::$req->post('is_hot', ['null', 'empty']);
                    $pageIndex = Cm::$req->post('page', ['null', 'empty', 'default' => 1]);
                    $pageCount = Cm::$req->post('limit', ['null', 'empty', 'default' => 20]);
                    $where = " 1=1 ";
                    if(!empty($hot)){
                        $hot = $hot == 2 ? 0 : $hot;
                        $where .= " AND c.is_hot={$hot}";
                    }
                    if(!empty($status)){
                        $status = $status == 2 ? 0 : $status;
                        $where .= " AND c.status={$status}";
                    }else{
                        $where .= " AND c.status!=2";
                    }
                    if(!empty($key)){
                        $where .= " AND c.name LIKE '%{$key}%'";
                    }
                    $data = Cm::$db->paging("SELECT c.*,(
                            SELECT CONCAT_WS('|',CONCAT_WS(',',province,city,full_name),parentpath) AS areas FROM open_city WHERE code=c.city_scode AND status=1
                        ) AS sarea,(
                            SELECT CONCAT_WS('|',CONCAT_WS(',',province,city,full_name),parentpath) AS areas FROM open_city WHERE code=c.city_ecode AND status=1
                        ) AS earea,(
                            SELECT full_name FROM site WHERE id=c.site_sid AND status=1
                        ) AS ssite,(
                            SELECT full_name FROM site WHERE id=c.site_eid AND status=1
                        ) AS esite,(
                            SELECT GROUP_CONCAT(name) AS tags FROM circuit_tag WHERE circuit_id=c.id AND status=1 ORDER BY sort
                        ) AS tags,(
                            SELECT CONCAT_WS(',',SUM(ridership),COUNT(id)) AS num FROM `order` WHERE circuit_id=c.id AND status=1 AND order_status<>5
                        ) AS orderstr
                        FROM circuit c
                        WHERE {$where} ",
                        $pageIndex, $pageCount);
                    foreach ($data['data'] as $key => &$value) {
                        if(!empty($value['sarea'])){
                            $arr = explode('|', $value['sarea']);
                            $value['scode']  = explode(',', $arr[1]);
                            $sarea = explode(',', $arr[0]);
                            if(count($value['scode'] ) == 1){
                                $value['sarea'] = $sarea[2];
                            }else if(count($value['scode'] ) == 2){
                                $value['sarea'] = $sarea[0].','.$sarea[2];
                            }
                        }else{
                            $value['sarea'] = '';
                            $value['scode'] = [];
                        }
                        if(!empty($value['earea'])){
                            $arr = explode('|', $value['earea']);
                            $value['ecode']  = explode(',', $arr[1]);
                            $earea = explode(',', $arr[0]);
                            if(count($value['ecode']) == 1){
                                $value['earea'] = $earea[2];
                            }else if(count($value['ecode'] ) == 2){
                                $value['earea'] = $earea[0].','.$earea[2];
                            }
                        }else{
                            $value['earea'] = '';
                            $value['ecode'] = [];
                        }
                        $orderstr = explode(",", $value['orderstr']);
                        $value['passengernum'] = $orderstr[0].'人';
                        $value['ordernum'] = empty($orderstr[1]) ? '0笔' : $orderstr[1].'笔';
                    }
                    Cm::$res->paging($data);
                    break;
                case 'save':
                    $id = Cm::$req->post('id', ['null', 'empty', 'default' => 0]);
                    $mdata = [
                        'name' => trim(Cm::$req->post('name',['title'=>'线路名称'])),
                        'serial_number' => trim(Cm::$req->post('serial_number',['title'=>'编码'])),
                        's_address' => trim(Cm::$req->post('s_address',['title'=>'上车地址'])),
                        'e_address' => trim(Cm::$req->post('e_address',['title'=>'下车地址'])),
                        'duration' => Cm::$req->post('duration', ['null', 'empty', 'default' => 0]),
                        'mileage' => Cm::$req->post('mileage', ['null', 'empty', 'default' => 0]),
                        'site_sid' => Cm::$req->post('site_sid', ['null', 'empty', 'default' => 0]),
                        'city_scode' => Cm::$req->post('city_scode', ['null', 'empty', 'default' => 0]),
                        'site_eid' => Cm::$req->post('site_eid', ['null', 'empty', 'default' => 0]),
                        'city_ecode' => Cm::$req->post('city_ecode', ['null', 'empty', 'default' => 0]),
                        'is_hot' => Cm::$req->post('is_hot', ['null', 'empty','default'=>0]),
                        'status' => Cm::$req->post('status',['null','empty','default'=>1]),
                        'updatetime' => date("Y-m-d H:i:s",time())
                    ];
                    if(empty($mdata['duration'])){
                        Cm::$res->error('保存失败,请填写时长');
                    }
                    if(empty($mdata['mileage'])){
                        Cm::$res->error('保存失败,请填写公里数');    
                    }
                    if(empty($mdata['site_sid']) || empty($mdata['city_scode'])){
                        Cm::$res->error('保存失败,请选择起始站点');
                    }
                    if(empty($mdata['site_eid']) ||empty($mdata['city_ecode'])){
                        Cm::$res->error('保存失败,请选择终点站点');
                    }
                    if($mdata['site_sid'] == $mdata['site_eid']){
                        Cm::$res->error('保存失败,起始站点和终点站点不能为同一站点');
                    }
                    if(!empty($id)){
                        Cm::$db->update('circuit', $mdata, "id={$id}");
                        Cm::$app->log->authlog(34,$mdata,$id);
                    }else{
                        $mdata['addtime'] = date('Y-m-d H:i:s');
                        $id = Cm::$db->insert('circuit', $mdata);
                        if(!$id){
                            Cm::$res->error('保存失败');
                        }
                        Cm::$app->log->authlog(33,$mdata,$id);
                    }
                    Cm::$res->susess([], '保存成功');
                    break;      
                case 'del':
                    $id = Cm::$req->post('id', ['null', 'empty', 'default' => 0]);
                    if(empty($id)){
                        Cm::$res->error('请选择删除开通的线路');
                    }
                    $mdata = ['status' => 2,'updatetime' => date("Y-m-d H:i:s",time())];
                    Cm::$db->update("circuit", $mdata, "id={$id}");
                    Cm::$app->log->authlog(35,$mdata,$id);
                    Cm::$res->susess();
                    break; 
                case 'tag_info':
                    $id = Cm::$req->post('id', ['null', 'empty', 'default' => 0]);
                    if(empty($id)){
                        Cm::$res->error('参数错误,请选择获取标签的线路');
                    }    
                    $tags = Cm::$db->all("SELECT * FROM circuit_tag WHERE circuit_id={$id} AND status=1 ORDER BY sort");
                    Cm::$app->log->authlog(36,$tags,$id);
                    Cm::$res->susess($tags);
                    break;    
                case 'tag_save':
                    $id = Cm::$req->post('id', ['null', 'empty', 'default' => 0]);
                    $mdata = [
                        'name' => trim(Cm::$req->post('name',['title'=>'标签名称'])),
                        'sort' => Cm::$req->post('sort',['null','empty','default'=>0]),
                        'circuit_id' => Cm::$req->post('circuit_id',['null','empty','default'=>0]),
                        'updatetime' => date("Y-m-d H:i:s",time())
                    ];
                    if(empty($mdata['circuit_id'])){
                        Cm::$res->error('参数错误,请选择保存标签的线路');
                    }
                    $hastag = Cm::$db->one("SELECT id FROM circuit_tag WHERE status=1 AND name='{$mdata['name']}' AND circuit_id={$mdata['circuit_id']} AND id!={$id}");
                    if(!empty($hastag)){
                        Cm::$res->error('该线路下已存在该标签');
                    }
                    if(!empty($id)){
                        Cm::$db->update('circuit_tag', $mdata, "id={$id}");
                        Cm::$app->log->authlog(37,$mdata,$id);
                    }else{
                        $mdata['addtime'] = date('Y-m-d H:i:s');
                        $mdata['status'] = 1;
                        $id = Cm::$db->insert('circuit_tag', $mdata);
                        if(!$id){
                            Cm::$res->error('保存失败');
                        }
                        Cm::$app->log->authlog(38,$mdata,$id);
                    }
                    $tags = Cm::$db->all("SELECT * FROM circuit_tag WHERE circuit_id={$mdata['circuit_id']} AND status=1 ORDER BY sort");
                    Cm::$res->susess($tags, '保存成功');    
                    break; 
                case 'tag_del':
                    $id = Cm::$req->post('id', ['null', 'empty', 'default' => 0]);
                    if(empty($id)){
                        Cm::$res->error('请选择删除的标签');
                    }
                    $mdata = ['status' => 2,'updatetime' => date("Y-m-d H:i:s",time())];
                    Cm::$db->update("circuit_tag", $mdata, "id={$id}");
                    Cm::$app->log->authlog(39,$mdata,$id);
                    Cm::$res->susess();
                    break;    
                case 'state':
                    $id = Cm::$req->post('id', ['null', 'empty', 'default' => 0]);
                    $status = Cm::$req->post('status', ['null', 'empty', 'default' => 1]);
                    if($status!=1 && $status!=0){
                        Cm::$res->error('操作错误！');
                    }
                    $str = $status == 1 ? '停用':'启用';
                    if(empty($id)){
                        Cm::$res->error('请选择要'.$str.'的线路');
                    }
                    $status = $status == 1 ? 0 : 1;
                    $mdata = ['status' => $status,'updatetime' => date("Y-m-d H:i:s",time())];
                    Cm::$db->update("circuit", $mdata, "id={$id}");
                    Cm::$app->log->authlog(40,$mdata,$id);
                    Cm::$res->susess();
                    break; 
                case 'order':
                    $id = Cm::$req->post('id', ['null', 'empty', 'default' => 0]);
                    if(empty($id)){
                        Cm::$res->error("请选择订单统计的线路");
                    }
                    $order = Cm::$db->all("SELECT COUNT(id) AS num,'isok' AS type FROM `order` WHERE circuit_id={$id} AND status=1 AND order_status<>5
                                        UNION ALL
                                        SELECT COUNT(id) AS num,'isno' AS type FROM `order` WHERE circuit_id={$id} AND order_status=5
                                        UNION ALL
                                        SELECT COUNT(id) AS num,'pay' AS type FROM `order` WHERE circuit_id={$id} AND pay_status=1 AND refund_status=0
                                        UNION ALL
                                        SELECT COUNT(id) AS num,'refund' AS type FROM `order` WHERE circuit_id={$id} AND status=2
                                        UNION ALL
                                        SELECT COUNT(id) AS num,'change' AS type FROM `order` WHERE circuit_id={$id} AND status=3
                                        UNION ALL
                                        SELECT COUNT(id) AS num,'cancel' AS type FROM `order` WHERE circuit_id={$id} AND status=0
                                        UNION ALL
                                        SELECT COUNT(id) AS num,'overtime' AS type FROM `order` WHERE circuit_id={$id} AND status=1 AND order_status=5");
                    $info = [];
                    $types = [
                        'isok' => '有效订单',
                        'isno' => '无效订单',
                        'pay' => '支付订单',
                        'refund' => '退款订单',
                        'change' => '改签订单',
                        'cancel' => '取消订单',
                        'overtime' => '超时订单'
                    ];
                    $info['data'] = [
                        'name' => "订单量",
                        'type' => "bar",
                        't' => "n",
                        'data' => [],
                        'label'=> [
                            'show'=> true,
                            'position'=> 'top'
                        ]
                    ];
                    foreach ($order as $s) {
                        $name = $types[$s['type']];
                        $info['name'][] = $name;
                        $info['data']['data'][] = $s['num'];
                    }
                    Cm::$res->susess($info);
                    break;         
            }
        }
        
        $data['map'] = [];
        $data['map'][] = ['title' => "站点管理", 'url' => Url::to(['site/index'])];
        $data['map'][] = ['title' => "线路管理", 'url' => Url::to(['circuit/index'])];
        $data['baseUrl'] = Url::to(['circuit/index']);
        $data['shiftUrl'] = Url::to(['shift/index']);
        $data['allSite'] = $this->allSite();
        $data['carModels'] = $this->carModels();
        $data['allInspector'] = $this->getInspector();
        return $data;
    }
}